﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace QKen.SPA.Common.Utility
{
    public class ValidateHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        #endregion

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Extract the forms authentication cookie
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpApplication application = sender as HttpApplication;
            HttpContext Context = application.Context;

            HttpCookie authCookie = Context.Request.Cookies[cookieName];

            if (null == authCookie)
            {
                // There is no authentication cookie.
                return;
            }
            FormsAuthenticationTicket authTicket = null;
            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                //authCookie.Expires = DateTime.Now.AddDays(1);
            }
            catch// (Exception ex)
            {
                // Log exception details (omitted for simplicity)
                return;
            }

            if (null == authTicket)
            {
                // Cookie failed to decrypt.
                return;
            }

            // When the ticket was created, the UserData property was assigned a
            // pipe delimited string of role names.
            //string[] roles = authTicket.UserData.Split('|');

            // Create an Identity object
            CrmUserIdentity identity = new CrmUserIdentity(authTicket);

            // This principal will flow throughout the request.
            CrmUserPrincipal principal = new CrmUserPrincipal(identity);

            // Attach the new principal object to the current HttpContext object
            Context.User = principal;
        }
    }
}
